<?php
defined('IN_MAIN') or exit('Invalid Access!');

function calc_prod_point($point_type, $prods){
/*
This function calculates total PV of all the products in the input $prods array, as:

$prods[index][id] = product id
$prods[index][refno] = product ref. no.
$prods[index][qty] = product qty

This function will use the product id 1st, if not exist, then it will use the ref. no. to search for the db
total pv is the product pv * qty for all the products in the input $prods
*/

	global $vars;
	$db=$vars["db"];

	for($i=0,$t=count($prods);$i<$t;$i++){
		if(strlen($prods[$i]["id"])){
			$pid.=($pid? "," : "")."'".$prods[$i]["id"]."'";
		}else{
			$refno.=($refno? "," : "")."'".$prods[$i]["refno"]."'";
		}
	}

	$pid_q=$pid? "id in ($pid)" : "";
	$refno_q=$refno? "refno in ($refno)" : "";
	$total_pv = 0;
	if($pid_q || $refno_q){
		$pq=$pid_q? $pid_q : "";
		$pq.=$refno_q? ($pq? " or " : "").$refno_q : "";
		$t=@mysql_num_rows($r=mysql_query($sql="select id, prod_type, refno, ".$point_type."_fix, $point_type from $db->products where $pq"));
		for($i=0;$i<$t;$i++){
			$prod=mysql_fetch_assoc($r);
			if($prod["prod_type"]=="p" && $prod[$point_type."_fix"]!="y"){
				$this_prod_point=calc_package_point($point_type, $prod["id"]);
			}else{
				$this_prod_point=$prod[$point_type];
			}
			$iprods[$prod["id"]]=$this_prod_point;
			$rprods[mysql_real_escape_string($prod["refno"])]=$this_prod_point;
		}
		for($i=0,$t=count($prods);$i<$t;$i++){
			if(strlen($prods[$i]["id"])){
				$total_point += $iprods[$prods[$i]["id"]] * $prods[$i]["qty"];
			}else{
				$total_point += $rprods[$prods[$i]["refno"]] * $prods[$i]["qty"];
			}
		}
	}

	return $total_point;
}

function calc_package_point($point_type, $pid, $key = 'id'){
/*
This function calculate the package total pv
*/

	global $vars;
	$db=$vars["db"];

	$total_point=0;
	$prod=@mysql_fetch_assoc(mysql_query("select * from $db->products where $key='$pid'"));
	if($prod){
		if($prod["prod_type"]!="p"){
			$total_point=$prod[$point_type];
		}elseif($prod[$point_type."_fix"]=="y"){
			$total_point=$prod[$point_type];
		}else{
			$t=@mysql_num_rows($r=mysql_query("select * from $db->package_detail where pkid='$prod[id]'"));
			for($i=0;$i<$t;$i++){
				$this_prod=mysql_fetch_assoc($r);
				$prods[$i]["id"]=$this_prod["pid"];
				$prods[$i]["qty"]=$this_prod["qty"];
			}
			$total_point=calc_prod_point($point_type, $prods);
		}
	}

	return $total_point;
}
?>